#!/bin/bash

help() {
    echo "usage: add_group.sh <user> [group]"
    echo "    if group is empty, group equals user"
    exit 1
}

if [[ "-h" == "$1" ]] || [[ "--help" == "$1" ]]; then
    help
fi

USER=$1
GROUP=$2

if [[ "" == "${USER}" ]]; then
    help
fi
if [[ "" == "${GROUP}" ]]; then
    GROUP=$USER
fi

echo "USER=${USER}"
echo "GROUP=${GROUP}"

# 添加新用户组
group_info=`grep -E "^${GROUP}:" /etc/group`
echo group_info=$group_info
if [[ "" == "$group_info" ]]; then
    # 用户组不存在，则添加用户组
    echo "add group ..."
    groupadd $GROUP
    ret=$?
    if [[ 0 -ne $ret ]]; then
        echo "$LINENO: add new group is failed. group=${GROUP}"
        exit $ret
    fi
    echo "group add success"
else
    echo "group \"${GROUP}\" exists"
fi

# 向组中添加新用户
id $USER
ret=$?
if [[ 0 -ne $ret ]]; then
    # 用户不存在，则添加用户
    echo "add user ..."
    useradd $USER -m -s /bin/bash -g $GROUP
    ret=$?
    if [[ 0 -ne $ret ]]; then
        echo "$LINENO: useradd is failed. user=${USER}"
        exit $ret
    fi
    echo "user add success"
else
    echo "user \"${USER}\" exists"
fi

echo "new user password:"
passwd $USER
ret=$?
if [[ 0 -ne $ret ]]; then
    echo "$LINENO: passwd ${USER} is failed. user=${USER}"
    echo $ret
fi
